// index.ts
// 获取应用实例
const app = getApp<IAppOption>()
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Component({
  data: {
    motto: 'Hello World',
    userInfo: {
      avatarUrl: defaultAvatarUrl,
      nickName: '',
    },
    hasUserInfo: false,
    canIUseGetUserProfile: wx.canIUse('getUserProfile'),
    canIUseNicknameComp: wx.canIUse('input.type.nickname'),
    showPopup: false,
    loading: true,
    poemError: false,
    currentPoem: {
      title: '',
      author: '',
      dynasty: '',
      content: [],
      type: '古诗',
      notes: [],
      appreciation: '',
      imageUrl: ''
    },
    poemTypes: ['全部', '古诗', '词', '曲', '赋'],
    formData: {
      keyword: '',
      author: '',
      type: '全部'
    }
  },
  lifetimes: {
    attached() {
      this.fetchDailyPoem();
    }
  },
  methods: {
    // 事件处理函数
    bindViewTap() {
      wx.navigateTo({
        url: '../logs/logs',
      })
    },
    onChooseAvatar(e: any) {
      const { avatarUrl } = e.detail
      const { nickName } = this.data.userInfo
      this.setData({
        "userInfo.avatarUrl": avatarUrl,
        hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
      })
    },
    onInputChange(e: any) {
      const nickName = e.detail.value
      const { avatarUrl } = this.data.userInfo
      this.setData({
        "userInfo.nickName": nickName,
        hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
      })
    },
    getUserProfile() {
      // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
      wx.getUserProfile({
        desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success: (res) => {
          console.log(res)
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    },
    // 获取今日古诗
    async fetchDailyPoem() {
      this.setData({
        loading: true,
        poemError: false
      });

      try {
        const result = await new Promise<any>((resolve, reject) => {
          wx.request({
            url: 'http://localhost:3000/api/daily-poem',
            method: 'GET',
            data: {
                keyword: "李白"
            },
            success: (res) => resolve(res),
            fail: (err) => reject(err)
          });
        });

        if (result.statusCode === 200 && result.data.success) {
          const poemData = result.data.data;
          
          this.setData({
            currentPoem: {
              title: poemData.title,
              author: poemData.author,
              dynasty: poemData.dynasty,
              content: poemData.content,
              type: poemData.type,
              notes: poemData.notes,
              appreciation: poemData.appreciation,
              imageUrl: poemData.imageUrl
            },
            loading: false
          });
        } else {
          console.error('获取古诗失败:', result.data);
          this.setData({
            loading: false,
            poemError: true
          });
        }
      } catch (error) {
        console.error('请求异常:', error);
        this.setData({
          loading: false,
          poemError: true
        });
      }
    },
    // 显示更换弹窗
    showChangePopup() {
      this.setData({
        showPopup: true
      });
    },
    // 隐藏弹窗
    hidePopup() {
      this.setData({
        showPopup: false
      });
    },
    // 处理输入变化
    onInput(e: any) {
      const { field } = e.currentTarget.dataset;
      const { value } = e.detail;
      
      this.setData({
        [`formData.${field}`]: value
      });
    },
    // 处理类型选择
    onTypeChange(e: any) {
      const { value } = e.detail;
      this.setData({
        'formData.type': this.data.poemTypes[value]
      });
    },
    // 确认更换古诗
    async confirmChange() {
      const { keyword, author, type } = this.data.formData;
      
      if (!keyword && !author) {
        wx.showToast({
          title: '请输入关键词或作者',
          icon: 'none'
        });
        return;
      }
      
      this.setData({
        showPopup: false,
        loading: true,
        poemError: false
      });

      try {
        const params: any = {};
        if (keyword) params.keyword = keyword;
        if (author) params.writer = author;
        if (type !== '全部') params.tags = type;

        const result = await new Promise<any>((resolve, reject) => {
          wx.request({
            url: 'http://localhost:3000/api/daily-poem',
            method: 'GET',
            data: params,
            success: (res) => resolve(res),
            fail: (err) => reject(err)
          });
        });

        if (result.statusCode === 200 && result.data.success) {
          const poemData = result.data.data;
          
          this.setData({
            currentPoem: {
              title: poemData.title,
              author: poemData.author,
              dynasty: poemData.dynasty,
              content: poemData.content,
              type: poemData.type,
              notes: poemData.notes,
              appreciation: poemData.appreciation,
              imageUrl: poemData.imageUrl
            },
            loading: false
          });

          wx.showToast({
            title: '古诗更换成功',
            icon: 'success'
          });
        } else {
          console.error('更换古诗失败:', result.data);
          this.setData({
            loading: false,
            poemError: true
          });
          
          wx.showToast({
            title: '更换古诗失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('请求异常:', error);
        this.setData({
          loading: false,
          poemError: true
        });
        
        wx.showToast({
          title: '网络异常',
          icon: 'none'
        });
      }
    },
    // 收藏功能
    toggleCollect() {
      wx.showToast({
        title: '收藏成功',
        icon: 'success'
      });
    },
    // 导航相关方法
    navigateTo(e: WechatMiniprogram.TouchEvent) {
      const page = e.currentTarget.dataset.page as string;
      wx.switchTab({
        url: `../${page}/${page}`
      });
    }
  },
})
